<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2023/6/17
 * Time: 15:07
 */
namespace app\admin\controller;

use app\middleware\AdminCheck;
use think\facade\Db;

class Car {

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [] ]
    ];

    /**
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getVehicleCode() {
        $car_vehicle_code = mt_rand(1000000000, 9999999999);
        if (!Db::name('cars')->where('car_vehicle_code', $car_vehicle_code)->find()) {
            return $car_vehicle_code;
        }

        return $this->getVehicleCode();
    }

    /**
     * @return \think\response\Json
     */
    public function storeCar() {
        validateParam('pics,car_name,test_drive_fee,brand_id,model_type,range,energy_type,charging_time,power,customize_attr','pics,car_name,test_drive_fee,brand_id,model_type,range,energy_type,charging_time,power,customize_attr');
        // 车辆编号生成规则
        //1、由10位啊拉伯数字组成，随机生成。
        //2、同车牌一样，具有唯一性。
        $data['car_name']=input('car_name');
        $data['type_name']=input('type_name');
//        $data['citys']=implode(',', input('citys'));
//        $data['car_no']=input('car_no');
        $data['test_drive_fee']=input('test_drive_fee');
        $data['brand_id'] = input('brand_id');
        $data['model_type'] = input('model_type');
        $data['range'] = input('range');
        $data['energy_type'] = input('energy_type');
        $data['charging_time'] = input('charging_time');
        $data['power'] = input('power');
        $data['pics'] = json_encode(input('pics'));
        $data['customize_attr'] = json_encode(input('customize_attr', []), JSON_UNESCAPED_UNICODE);
        if (!input('id')) {
            $data['status'] = 1;
            $data['car_vehicle_code'] = $this->getVehicleCode();

            $res = Db::name('cars')->insert($data);
        } else {
            $res = Db::name('cars')->where('id', input('id'))->update($data);
        }
        return success('添加成功', $res);
    }

    /**
     * 车辆列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('pageNo,pageSize','pageNo,pageSize');
        $param = input();
        $where = [];

        $query = Db::name('cars')
            ->where($where);
        if (isset($param['car_name']) && !empty($param['car_name'])) {
            $query->whereLike('car_name', "%{$param['car_name']}%");
        }
        $total = $query->count();

        $offset = makeOffset($param['pageNo'],$param['pageSize']);
        $list = $query
            ->field('*')
            ->limit($offset,$param['pageSize'])
            ->where($where)
            ->order('id desc')
            ->select()->toArray();
        foreach ($list as &$val) {
            if ($val['customize_attr']) {
                $val['customize_attr'] = json_decode($val['customize_attr'], true);
            }
            $carNos = Db::name('car_nos')
                ->join('region', 'region.region_id=car_nos.region_id')
                ->where(['car_id' => $val['id'], 'is_deleted' => 0])
                ->field(['region.region_name', 'status'])
                ->select();

            if (!empty($carNos)) {
                $carNos = collect($carNos->toArray());
                $val['citys'] = $carNos->column('region_name');
                $val['nums'] = $carNos->count();
                $val['up_nums'] = $carNos->where('status', '=', 1)->count();
                $val['down_nums'] = $carNos->where('status', '=', 0)->count();
            };
        }

        return success('车辆列表',['total'=>$total,'list'=>$list]);
    }

    /**
     * 车型车辆列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCarNoList(){
        validateParam('pageNo,pageSize','pageNo,pageSize');
        $param = input();
        $where = [];

        $query = Db::name('cars')
            ->where($where);
        if (isset($param['car_name']) && !empty($param['car_name'])) {
            $query->whereLike('car_name', $param['car_name']);
        }
        $total = $query->count();

        $offset = makeOffset($param['pageNo'],$param['pageSize']);
        $list = $query
            ->field('*')
            ->limit($offset,$param['pageSize'])
            ->where($where)
            ->order('id desc')
            ->select()->toArray();
        foreach ($list as &$val) {
            if ($val['customize_attr']) {
                $val['customize_attr'] = json_decode($val['customize_attr'], true);
            }
            $carNos = Db::name('car_nos')
                ->join('region', 'region.region_id=car_nos.region_id')
                ->where(['car_id' => $val['id'], 'is_deleted' => 0])
                ->field(['region.region_name', 'status'])
                ->select();

            if (!empty($carNos)) {
                $carNos = collect($carNos->toArray());
                $val['citys'] = $carNos->column('region_name');
                $val['nums'] = $carNos->count();
                $val['up_nums'] = $carNos->where('status', '=', 1)->count();
                $val['down_nums'] = $carNos->where('status', '=', 0)->count();
            };
        }

        return success('车辆列表',['total'=>$total,'list'=>$list]);
    }

    /**
     * 更新上下架状态
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function updateStatus() {
        validateParam('id','id');
        Db::name('cars')->where('id', input('id'))->update(['status' => input('status', 0)]);
        return success('更新成功');
    }

    /**
     * 更新试驾费用
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function updateDriverFee() {
        $params = validateParam('id,test_drive_fee','id,test_drive_fee');
        Db::name('cars')->where('id', input('id'))->update(['test_drive_fee' => $params['test_drive_fee']]);
        return success('更新成功');
    }
}